/*
ID:luongho3
LANG:C++
TASK:comehome
*/
#include <iostream>
#include <fstream>

using namespace std;
ifstream fin("comehome.in");
ofstream fout("comehome.out");
#define N_PASTURES 60
#define INF 2000000000
int nPath;
int m[N_PASTURES][N_PASTURES];
int label[N_PASTURES],occupied[N_PASTURES],hasCow[N_PASTURES];

int getPastureIndex(char c) {
    if (islower(c)) {
       return c - 'a' + 1;
    }
    else if (isupper(c)) {
         return c - 'A' + 1 + 26;
    }
}

void init() {
     int i,j;
     for (i=0;i<N_PASTURES;++i) {
         for (j=0;j<=i;++j) {
             m[i][j] = m[j][i] = INF;
         }
         m[i][i] = 0;
         label[i] = INF;
         occupied[i] = 0;
         hasCow[i] = 0;
     }
}
void readPath() {
     int i, s_index, d_index, path_len;
     char src, dst;
     for (i=1;i<=nPath;++i) {
         fin >> src >> dst >> path_len;
         s_index = getPastureIndex(src);
         d_index = getPastureIndex(dst);
         if (s_index == d_index) {
            // src and dst are the same --> discard the path
            continue;
         }
         else {
              // src and dst are different --> get the smaller of the old and the new path
              m[s_index][d_index] = m[s_index][d_index] < path_len ? m[s_index][d_index] : path_len;
              m[d_index][s_index] = m[s_index][d_index];
         }
         //check for cow's presence at the src and dst
         if (isupper(src) && src != 'Z') {
            hasCow[s_index] = 1;
         }
         if (isupper(dst) && dst != 'Z') {
            hasCow[d_index] = 1;
         }
     }
}
int main() {
    fin >> nPath;
    init();
    readPath();
    // run a greedy algorithm from the barn, whichever cow is reached first is the solution
    int barn_index = getPastureIndex('Z');
    int nPastures = barn_index;
    label[barn_index] = 0;
    hasCow[barn_index] = 0;
    //occupied[barn_index] = 1;
    int i,j,key,minVal;
    for (i=1;i<=nPastures;++i) {
        minVal = INF;
        key = -1;
        for (j=1;j<=nPastures;++j) {
            if (label[j] < minVal && occupied[j] == 0) {
               minVal = label[j];
               key = j;
            }
        }
        if (key == -1) break;
        occupied[key] = 1;
        if (hasCow[key] == 1) {
           fout << (char)(key - 26 - 1 + 'A') << " " << label[key] << "\n";
           break;
        }
        for (j=1;j<=nPastures;++j) {
            if (j != key && m[j][key] < INF) {
               label[j] = label[j] < (label[key] + m[j][key]) ? label[j] : (label[key] + m[j][key]);
            }
        }
    }
    return 0;
}
